//package com.example.authorization.conf;
//
//import cn.hutool.core.util.IdUtil;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
//import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
//import org.springframework.security.core.GrantedAuthority;
//import org.springframework.security.core.userdetails.UserDetails;
//import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames;
//import org.springframework.security.oauth2.jwt.JwtClaimsSet;
//import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
//import org.springframework.security.oauth2.server.authorization.token.JwtEncodingContext;
//import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenCustomizer;
//
//import java.security.KeyPair;
//import java.security.KeyPairGenerator;
//import java.util.List;
//import java.util.Set;
//import java.util.stream.Collectors;
//
//@Configuration
//@EnableWebSecurity
//@EnableMethodSecurity(jsr250Enabled = true, securedEnabled = true)
//public class SecurityConfig {
//
//
//
//
//
//    /**
//     * 配置一个基于内存的 客户端 信息
//     *
//     * @return
//     */
////    @Bean
////    public RegisteredClientRepository registeredClientRepository() {
////        RegisteredClient oidcClient = RegisteredClient.withId(UUID.randomUUID().toString())
////                .clientId("first-client")
////                .clientSecret("{noop}first-client-secret")
////                // 基于请求头的客户端认证方式
////                .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
////                //基于表单参数的客户端认证方式
////                //.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST)
////                //资源服务器使用该客户端获取授权时支持的方式
////                .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
////                .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
////                // 授权码模式回调地址
////                .redirectUri("https://www.baidu.com")
////                // 该客户端的授权范围，OPENID与PROFILE是IdToken的scope，获取授权时请求OPENID的scope时认证服务会返回IdToken
////                .scope(OidcScopes.OPENID)
////                .scope(OidcScopes.PROFILE)
////                // 自定scope
////                .scope("message.read")
////                //设置客户端 是否需要授权,如果为 false 将不会跳到授权页
////                .clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build())
////                .build();
////
////        RegisteredClient pkce = RegisteredClient.withId(UUID.randomUUID().toString())
////                .clientId("pkce-client")
////                .clientSecret("{noop}pkce-client-secret")
////                .clientAuthenticationMethod(ClientAuthenticationMethod.NONE)
////                .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
////                .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
////                .redirectUri("https://www.baidu.com")
////                .scope(OidcScopes.OPENID)
////                .scope(OidcScopes.PROFILE)
////                .scope("message.read")
////                //设置客户端 使用 proofKey
////                .clientSettings(ClientSettings.builder().requireProofKey(true).build())
////                .build();
////
////
////        return new InMemoryRegisteredClientRepository(Arrays.asList(pkce,oidcClient));
////    }
//
//
//
//
//
//
//    /**
//     * 配置jwk源，使用非对称加密
//     *
//     * @return
//     */
////    @Bean
////    public JWKSource<SecurityContext> jwkSource() {
////        KeyPair keyPair = generateRsaKey();
////        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
////        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
////        RSAKey rsaKey = new RSAKey.Builder(publicKey)
////                .privateKey(privateKey)
////                .keyID(UUID.randomUUID().toString())
////                .build();
////        JWKSet jwkSet = new JWKSet(rsaKey);
////        return new ImmutableJWKSet<>(jwkSet);
////    }
//
//    private static KeyPair generateRsaKey() {
//        KeyPair keyPair;
//        try {
//            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
//            keyPairGenerator.initialize(2048);
//            keyPair = keyPairGenerator.generateKeyPair();
//        } catch (Exception ex) {
//            throw new IllegalStateException(ex);
//        }
//        return keyPair;
//    }
//
////    /**
////     * 配置jwt解析器
////     *
////     * @param jwkSource jwk源
////     * @return JwtDecoder
////     */
////    @Bean
////    public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
////        return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource);
////    }
//
//
//
//
//
////    @Bean
////    public JwtEncoder jwtEncoder() {
////        return new NimbusJwtEncoder(jwkSource());
////    }
//
////    @Bean
////    public OAuth2TokenGenerator<?> tokenGenerator() {
////        JwtGenerator jwtGenerator = new JwtGenerator(jwtEncoder());
////        jwtGenerator.setJwtCustomizer(jwtCustomizer());
////        OAuth2AccessTokenGenerator accessTokenGenerator = new OAuth2AccessTokenGenerator();
////        OAuth2RefreshTokenGenerator refreshTokenGenerator = new OAuth2RefreshTokenGenerator();
////        return new DelegatingOAuth2TokenGenerator(jwtGenerator, accessTokenGenerator, refreshTokenGenerator);
////    }
//
//    @Bean
//    public OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer() {
//        return context -> {
//            JwtClaimsSet.Builder claims = context.getClaims();
//            Object principal = context.getPrincipal().getPrincipal();
//            if (principal instanceof UserDetails user) {
//                List<String> collect = user.getAuthorities().stream().map(GrantedAuthority::getAuthority).distinct().collect(Collectors.toList());
//                claims.claim("roles", collect);
//                Set<String> authorizedScopes = context.getAuthorizedScopes();
//                collect.addAll(authorizedScopes);
//                claims.claim("authorities", collect);
//            }
//
//            if (context.getTokenType().equals(OAuth2TokenType.ACCESS_TOKEN)) {
//                // Customize headers/claims for access_token
//                claims.claim("id", IdUtil.fastSimpleUUID());
//            } else if (context.getTokenType().getValue().equals(OidcParameterNames.ID_TOKEN)) {
//                // Customize headers/claims for id_token
//
//            }
//        };
//    }
//
//
////    @Bean
////    public JwtAuthenticationConverter jwtAuthenticationConverter() {
////        JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
////        grantedAuthoritiesConverter.setAuthorityPrefix("");
////        grantedAuthoritiesConverter.setAuthoritiesClaimName("authorities");
////        JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
////        jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
////        return jwtAuthenticationConverter;
////    }
//
//}